const { app, BrowserWindow, Menu, ipcMain, dialog, Tray } = require('electron');
const path = require('path');

// 保持对窗口对象的全局引用
let mainWindow;
let miniWindow;
let tray = null;

function createWindow() {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, '../../assets/icon.png'),
    show: false,
    titleBarStyle: 'default'
  });

  // 加载应用的index.html
  mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));

  // 当窗口准备好时显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  // 当窗口被关闭时触发
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

function createMiniWindow() {
  // 获取屏幕尺寸
  const { screen } = require('electron');
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize;
  
  // 创建小窗口
  miniWindow = new BrowserWindow({
    width: 400,
    height: 600,
    minWidth: 300,
    minHeight: 500,
    maxWidth: 500,
    maxHeight: 700,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, '../../assets/icon.png'),
    show: true,
    frame: false,  // 隐藏标题栏
    resizable: true,
    alwaysOnTop: false,
    skipTaskbar: false,
    // 定位到右下角
    x: width - 400,
    y: height - 620
  });

  // 加载小页面
  miniWindow.loadFile(path.join(__dirname, '../renderer/mini.html'));

  // 当小窗口被关闭时触发
  miniWindow.on('closed', () => {
    miniWindow = null;
  });

  // 小窗口最小化时隐藏到托盘
  miniWindow.on('minimize', () => {
    miniWindow.hide();
  });
}

function createTray() {
  try {
    // 暂时跳过系统托盘创建，因为图标文件可能有问题
    console.log('Skipping tray creation due to icon issues');
    return;
    
    // 创建系统托盘 - 使用绝对路径
    const iconPath = path.join(__dirname, '../../assets/icon.png');
    console.log('Tray icon path:', iconPath);
    tray = new Tray(iconPath);
    
    // 设置托盘菜单
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示小助手',
        click: () => {
          if (miniWindow) {
            miniWindow.show();
            miniWindow.focus();
          }
        }
      },
      {
        label: '显示主界面',
        click: () => {
          if (mainWindow) {
            mainWindow.show();
            mainWindow.focus();
          }
        }
      },
      { type: 'separator' },
      {
        label: '关于',
        click: () => {
          dialog.showMessageBox(mainWindow || miniWindow, {
            type: 'info',
            title: '关于 AI 电脑管家',
            message: 'AI 电脑管家',
            detail: '七牛云秋招项目 - 基于大模型的智能桌面助手'
          });
        }
      },
      { type: 'separator' },
      {
        label: '退出',
        click: () => {
          app.quit();
        }
      }
    ]);
    
    tray.setContextMenu(contextMenu);
    tray.setToolTip('AI 电脑管家');
    
    // 双击托盘图标显示小窗口
    tray.on('double-click', () => {
      if (miniWindow) {
        miniWindow.show();
        miniWindow.focus();
      }
    });
  } catch (error) {
    console.error('Failed to create system tray:', error);
  }
}

// 当Electron完成初始化并准备创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  // 默认创建小窗口，主窗口隐藏
  createMiniWindow();
  createWindow();
  mainWindow.hide(); // 隐藏主窗口
  createTray(); // 创建系统托盘

  app.on('activate', () => {
    // 在macOS上，当单击dock图标并且没有其他窗口打开时，
    // 通常在应用程序中重新创建窗口
    if (BrowserWindow.getAllWindows().length === 0) {
      createMiniWindow();
      createWindow();
      mainWindow.hide();
      createTray();
    }
  });
});

// 当所有窗口都被关闭时退出应用
app.on('window-all-closed', () => {
  // 在macOS上，除非用户用Cmd + Q确定地退出，
  // 否则绝大部分应用及其菜单栏会保持激活
  if (process.platform !== 'darwin') {
    // 不直接退出，让应用在托盘中运行
    // app.quit();
  }
});

// 应用退出前清理托盘
app.on('before-quit', () => {
  if (tray) {
    tray.destroy();
  }
});

// 创建应用菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建项目',
          accelerator: 'CmdOrCtrl+N',
          click: () => {
            mainWindow.webContents.send('menu-new-project');
          }
        },
        {
          label: '导入数据',
          accelerator: 'CmdOrCtrl+I',
          click: async () => {
            const result = await dialog.showOpenDialog(mainWindow, {
              properties: ['openFile'],
              filters: [
                { name: '数据文件', extensions: ['csv', 'xlsx', 'json'] },
                { name: '所有文件', extensions: ['*'] }
              ]
            });
            
            if (!result.canceled) {
              mainWindow.webContents.send('menu-import-data', result.filePaths[0]);
            }
          }
        },
        {
          label: '导出报告',
          accelerator: 'CmdOrCtrl+E',
          click: async () => {
            const result = await dialog.showSaveDialog(mainWindow, {
              filters: [
                { name: 'PDF 报告', extensions: ['pdf'] },
                { name: 'Excel 文件', extensions: ['xlsx'] },
                { name: '所有文件', extensions: ['*'] }
              ]
            });
            
            if (!result.canceled) {
              mainWindow.webContents.send('menu-export-report', result.filePath);
            }
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'AI 助手',
      submenu: [
        {
          label: '语音控制',
          accelerator: 'CmdOrCtrl+Space',
          click: () => {
            mainWindow.webContents.send('ai-voice-control');
          }
        },
        {
          label: '媒体控制',
          accelerator: 'CmdOrCtrl+M',
          click: () => {
            mainWindow.webContents.send('ai-media-control');
          }
        },
        {
          label: '生产力工具',
          accelerator: 'CmdOrCtrl+P',
          click: () => {
            mainWindow.webContents.send('ai-productivity');
          }
        },
        {
          label: '系统控制',
          accelerator: 'CmdOrCtrl+S',
          click: () => {
            mainWindow.webContents.send('ai-system-control');
          }
        },
        { type: 'separator' },
        {
          label: 'AI 设置',
          click: () => {
            mainWindow.webContents.send('ai-settings');
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'undo', label: '撤销' },
        { role: 'redo', label: '重做' },
        { type: 'separator' },
        { role: 'cut', label: '剪切' },
        { role: 'copy', label: '复制' },
        { role: 'paste', label: '粘贴' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { role: 'reload', label: '重新加载' },
        { role: 'forceReload', label: '强制重新加载' },
        { role: 'toggleDevTools', label: '开发者工具' },
        { type: 'separator' },
        { role: 'resetZoom', label: '实际大小' },
        { role: 'zoomIn', label: '放大' },
        { role: 'zoomOut', label: '缩小' },
        { type: 'separator' },
        { role: 'togglefullscreen', label: '全屏' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: '关于',
              message: 'Electron应用',
              detail: '这是一个简单的Electron应用'
            });
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// IPC通信处理
ipcMain.handle('get-app-version', () => {
  return app.getVersion();
});

// 窗口切换处理
ipcMain.handle('show-main-window', () => {
  if (mainWindow) {
    mainWindow.show();
    mainWindow.focus();
  }
});

ipcMain.handle('show-mini-window', () => {
  if (miniWindow) {
    miniWindow.show();
    miniWindow.focus();
  }
});

ipcMain.handle('hide-main-window', () => {
  if (mainWindow) {
    mainWindow.hide();
  }
});

ipcMain.handle('hide-mini-window', () => {
  if (miniWindow) {
    miniWindow.hide();
  }
});

ipcMain.handle('show-message-box', async (event, options) => {
  const result = await dialog.showMessageBox(mainWindow, options);
  return result;
});

ipcMain.handle('show-save-dialog', async (event, options) => {
  const result = await dialog.showSaveDialog(mainWindow, options);
  return result;
});

ipcMain.handle('show-open-dialog', async (event, options) => {
  const result = await dialog.showOpenDialog(mainWindow, options);
  return result;
});

// AI 电脑管家相关 IPC 处理
const { exec, spawn } = require('child_process');
const os = require('os');

// 语音控制处理
ipcMain.handle('ai-voice-control', async (event, command) => {
  try {
    // 模拟语音控制功能
    return {
      success: true,
      message: '语音控制已激活',
      action: 'voice_control_activated'
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 媒体控制处理
ipcMain.handle('ai-media-control', async (event, action, params) => {
  try {
    let result = { success: true };
    
    switch (action) {
      case 'play_music':
        // 模拟播放音乐
        result.message = '正在播放音乐...';
        result.action = 'music_playing';
        break;
      case 'pause_music':
        result.message = '音乐已暂停';
        result.action = 'music_paused';
        break;
      case 'adjust_volume':
        result.message = `音量已调整为 ${params.volume}%`;
        result.action = 'volume_adjusted';
        break;
      case 'next_track':
        result.message = '切换到下一首';
        result.action = 'track_changed';
        break;
      default:
        result.message = '媒体控制功能已执行';
    }
    
    return result;
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 生产力工具处理
ipcMain.handle('ai-productivity', async (event, action, params) => {
  try {
    let result = { success: true };
    
    switch (action) {
      case 'write_article':
        result.message = '正在为您生成文章...';
        result.content = `# ${params.title || 'AI 生成的文章'}\n\n${params.content || '这是一篇由 AI 生成的文章内容。'}`;
        result.action = 'article_generated';
        break;
      case 'create_document':
        result.message = '文档已创建';
        result.filePath = `~/Documents/${params.filename || '新文档.txt'}`;
        result.action = 'document_created';
        break;
      case 'send_email':
        result.message = `邮件已发送给 ${params.recipient}`;
        result.action = 'email_sent';
        break;
      case 'create_task':
        result.message = '任务已添加到待办清单';
        result.action = 'task_created';
        break;
      default:
        result.message = '生产力工具功能已执行';
    }
    
    return result;
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 系统控制处理
ipcMain.handle('ai-system-control', async (event, action, params) => {
  try {
    let result = { success: true };
    
    switch (action) {
      case 'open_application':
        result.message = `正在打开 ${params.app || '应用程序'}`;
        result.action = 'app_opening';
        break;
      case 'close_application':
        result.message = '应用程序已关闭';
        result.action = 'app_closed';
        break;
      case 'system_info':
        result.message = '系统信息获取完成';
        result.info = {
          platform: os.platform(),
          arch: os.arch(),
          totalMemory: Math.round(os.totalmem() / 1024 / 1024 / 1024) + 'GB',
          freeMemory: Math.round(os.freemem() / 1024 / 1024 / 1024) + 'GB',
          cpuCount: os.cpus().length
        };
        result.action = 'system_info_retrieved';
        break;
      case 'file_operation':
        result.message = '文件操作已完成';
        result.action = 'file_operation_completed';
        break;
      case 'system_optimization':
        result.message = '系统优化已完成';
        result.action = 'system_optimized';
        break;
      default:
        result.message = '系统控制功能已执行';
    }
    
    return result;
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 复杂场景自动化处理
ipcMain.handle('ai-automation', async (event, scenario, params) => {
  try {
    let result = { success: true, steps: [] };
    
    switch (scenario) {
      case 'morning_routine':
        result.steps = [
          '检查邮件',
          '播放晨间音乐',
          '打开工作文档',
          '设置提醒事项'
        ];
        result.message = '晨间例行程序已启动';
        result.action = 'morning_routine_started';
        break;
      case 'work_session':
        result.steps = [
          '关闭娱乐应用',
          '打开工作环境',
          '设置专注模式',
          '启动计时器'
        ];
        result.message = '工作会话已配置';
        result.action = 'work_session_configured';
        break;
      case 'content_creation':
        result.steps = [
          '收集相关资料',
          '生成内容大纲',
          '创建文档',
          '保存到指定位置'
        ];
        result.message = '内容创作流程已启动';
        result.action = 'content_creation_started';
        break;
      case 'system_maintenance':
        result.steps = [
          '清理临时文件',
          '检查系统状态',
          '优化性能',
          '生成维护报告'
        ];
        result.message = '系统维护已开始';
        result.action = 'maintenance_started';
        break;
      default:
        result.message = '自动化场景已执行';
    }
    
    return result;
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// 大模型集成处理
ipcMain.handle('ai-llm-process', async (event, prompt, context) => {
  try {
    // 模拟大模型处理
    const responses = {
      'play_music': '我将为您播放音乐。正在搜索您喜欢的歌曲...',
      'write_article': '我来帮您写一篇文章。请告诉我您想要的主题和内容要求。',
      'system_control': '我将帮您控制系统。请告诉我您想要执行的具体操作。',
      'automation': '我将为您创建一个自动化工作流程。让我分析您的需求...',
      'general': '我理解您的需求。让我为您提供最合适的解决方案。'
    };
    
    const response = responses[context] || responses['general'];
    
    return {
      success: true,
      response: response,
      confidence: 0.95,
      timestamp: new Date().toISOString()
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
});